package common.spring.interceptor;


import common.pojo.CommonResult;
import common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public abstract class BaseInterceptor extends HandlerInterceptorAdapter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    final protected void writerHtmlToBody(HttpServletResponse response, String result) {
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(result);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
        }
    }

    final protected void writerJsonToBody(HttpServletResponse response, Object obj) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JsonUtils.toJson(obj));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
        }
    }

    final protected boolean isAjax(HttpServletRequest request){
        return request.getHeader("x-requested-with") != null && "XMLHttpRequest".equals(request.getHeader("x-requested-with").toString());
    }

    final protected boolean returnDataWrapper(HttpServletResponse response,Object... obj) {
        return returnSuccessWrapper(response,obj);
    }

    final protected boolean returnWrapper(HttpServletResponse response, int code, String message, Object... obj) {
        CommonResult result = new CommonResult();
        result.setMessage(message);
        if (obj != null && obj.length == 1) {
            result.setData(obj[0]);
        } else {
            result.setData(obj);
        }
        result.setCode(code);
        logger.debug(String.format("service return code : %s,message:%s", code, message));
        writerJsonToBody(response,result);
        return false;
    }

    final protected boolean returnBoolWrapper(HttpServletResponse response, boolean bool, String fails, Object... obj) {
        if (bool) {
            return returnSuccessWrapper(response,obj);
        }
        return returnFailsWrapper(response,fails, obj);
    }

    final protected boolean returnSuccessWrapper(HttpServletResponse response,Object... obj) {
        return returnWrapper(response, CommonResult.SUCCESS, "success", obj);
    }

    final protected boolean returnFailsWrapper(HttpServletResponse response, String message, Object... obj) {
        return returnWrapper(response, CommonResult.FAILS, message, obj);
    }
}
